/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.pro.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.EhCacheUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.MailUtil;
import com.thinkgem.jeesite.common.utils.Preview;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.pro.dao.ProjectTaskDao;
import com.thinkgem.jeesite.modules.pro.entity.Document;
import com.thinkgem.jeesite.modules.pro.entity.Folder;
import com.thinkgem.jeesite.modules.pro.entity.ProLog;
import com.thinkgem.jeesite.modules.pro.entity.Project;
import com.thinkgem.jeesite.modules.pro.entity.ProjectTask;
import com.thinkgem.jeesite.modules.pro.entity.TaskGroup;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;

/**
 * 任务管理Service
 * @author fanqinglong
 * @version 2017-04-25
 */
@Service
@Transactional(readOnly = true)
public class ProjectTaskService extends CrudService<ProjectTaskDao, ProjectTask> {
	@Autowired
	private DocumentService documentService;
	@Autowired
	private FolderService folderService;
	@Autowired
	private ProLogService proLogService;
	@Autowired
	private TaskGroupService taskGroupService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ProjectService projectService;

	public ProjectTask get(String id) {
		return super.get(id);
	}
	
	public List<ProjectTask> findList(ProjectTask projectTask) {
		return super.findList(projectTask);
	}
	
	public List<ProjectTask> findListForPanel(ProjectTask projectTask){
		return dao.findListForPanel(projectTask);
	}
	
	public Page<ProjectTask> findPage(Page<ProjectTask> page, ProjectTask projectTask) {
		return super.findPage(page, projectTask);
	}
	/**
	 * 校验一个项目组下面是否还有未完成的任务
	 * @param groupId
	 * @return
	 */
	public Integer findByGroupIdAndStatus(String groupId){
		return dao.findByGroupIdAndStatus(groupId);
	}
	
	/**
	 * 校验一个项目下面是否还有未完成的任务
	 * @param projectTask
	 * @return
	 */
	public Integer findByProjectIdAndStatus(ProjectTask projectTask){
		return dao.findByProjectIdAndStatus(projectTask);
	}
	
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public void save(HttpServletRequest request, ProjectTask projectTask) {
		boolean flag = StringUtils.isEmpty(projectTask.getId());
		User manager = systemService.getUser(projectTask.getManager().getId());
		//不是新增
		if (!flag) {
			ProjectTask projectTaskSaved = dao.get(projectTask.getId());
			if (!manager.getId().equals(projectTaskSaved.getManager().getId())) {
				//发送邮件
				if (!StringUtils.isEmpty(manager.getEmail())) {
					StringBuffer sb = new StringBuffer();
					sb.append(manager.getName());
					sb.append(",你在[");
					sb.append(projectTaskSaved.getProject().getName());
					sb.append("]项目中有一个新任务为[");
					sb.append(projectTaskSaved.getName());
					sb.append("]");
					MailUtil.SendMail(manager.getEmail(), "任务分配通知", sb.toString());
				}
			}
		}else{
			Project project = projectService.get(projectTask.getProject().getId());
			//发送邮件
			if (!StringUtils.isEmpty(manager.getEmail())) {
				StringBuffer sb = new StringBuffer();
				sb.append(manager.getName());
				sb.append(",你在[");
				sb.append(project.getName());
				sb.append("]项目中有一个新任务为[");
				sb.append(projectTask.getName());
				sb.append("]");
				MailUtil.SendMail(manager.getEmail(), "任务分配通知", sb.toString());
			}
		}
		if (null != projectTask.getTaskGroup() && flag) {
			TaskGroup taskGroup = taskGroupService.get(projectTask.getTaskGroup().getId());
			if (null != taskGroup.getProject()) {
				projectTask.setProject(taskGroup.getProject());
			}
		}
		super.save(projectTask);
		String items = request.getParameter("items");
		String[] names = null;
		String realNameString = request.getParameter("realNames");
		String[] realNames = null;
		if (!StringUtils.isEmpty(items)) {
			names = items.split(",");
		}
		if (!StringUtils.isEmpty(realNameString)) {
			realNames = realNameString.split(",");
		}
		if (null != names) {
			Folder folder = folderService.findByGroupId(projectTask.getTaskGroup().getId());
			for (int i = 0; i < names.length; i++) {
				Document document = new Document();
				document.setSrc(names[i]);
				document.setFolder(folder);
				document.setName(realNames[i]);
				document.setRealName(realNames[i]);
				document.setTask(projectTask);
				documentService.save(document);
			}
		}
		//项目日志
		ProLog proLog = new ProLog();
		proLog.setModule(ProLog.TASK);
		proLog.setModuleid(projectTask.getId());
		proLog.setData(JsonMapper.toJsonString(projectTask));
		proLog.setType(flag?ProLog.CREATE:ProLog.UPDATE);
		proLog.setProject(projectTask.getProject());
		proLogService.save(proLog);
	}
	
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public void updateFromGantt(ProjectTask projectTask){
		projectTask.preUpdate();
		dao.updateFromGantt(projectTask);
		ProjectTask projectTaskNew = get(projectTask.getId());
		//项目日志
		ProLog proLog = new ProLog();
		proLog.setModule(ProLog.TASK);
		proLog.setModuleid(projectTask.getId());
		proLog.setData(JsonMapper.toJsonString(projectTaskNew));
		proLog.setType(ProLog.UPDATE);
		proLog.setProject(projectTaskNew.getProject());
		proLogService.save(proLog);
	}
	
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public void delete(ProjectTask projectTask) {
		super.delete(projectTask);
		User manager = systemService.getUser(projectTask.getManager().getId());
		ProjectTask projectTaskSaved = dao.get(projectTask.getId());
		//发送邮件
		if (!StringUtils.isEmpty(manager.getEmail())) {
			StringBuffer sb = new StringBuffer();
			sb.append(manager.getName());
			sb.append(",你在[");
			sb.append(projectTaskSaved.getProject().getName());
			sb.append("]项目中的[");
			sb.append(projectTaskSaved.getName());
			sb.append("]任务已完成");
			MailUtil.SendMail(manager.getEmail(), "任务完成通知", sb.toString());
		}
		//项目日志
		ProLog proLog = new ProLog();
		proLog.setModule(ProLog.TASK);
		proLog.setModuleid(projectTask.getId());
		proLog.setData(JsonMapper.toJsonString(projectTask));
		proLog.setType(ProLog.DELETE);
		proLog.setProject(projectTask.getProject());
		proLogService.save(proLog);
	}
	
	public ProjectTask getByName(ProjectTask projectTask){
		return dao.getByName(projectTask);
	}
	
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public Preview<ProjectTask> getPreview(HttpServletRequest request,MultipartFile file,String projectId){
		List<ProjectTask> list = null;
		try{
			if (!file.isEmpty()) {
				ImportExcel ei = new ImportExcel(file, 1, 0);
				list = ei.getDataList(ProjectTask.class);
			}
		}catch (InvalidFormatException | IOException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		if (null == list || list.size() == 0) {
			return new Preview<>();
		}
		// 校验通过的list
		List<ProjectTask> validList = new ArrayList<>();
		// 校验失败的list
		List<ProjectTask> failList = new ArrayList<>();
		// 查询参数，project
		Project project = new Project(projectId);
		Preview<ProjectTask> preview = new Preview<>();
		for (int i = 0; i < list.size(); i++) {
			ProjectTask projectTask = list.get(i);
			//校验优先级是否错误
			if (StringUtils.isEmpty(projectTask.getPriority())) {
				projectTask.setFailReason("5");
				failList.add(projectTask);
				continue;
			}
			//校验负责人是否合法
			if (null == projectTask.getManager()) {
				projectTask.setFailReason("4");
				failList.add(projectTask);
				continue;
			}
			//校验日期合法
			if (null != projectTask.getStartTime() && projectTask.getStartTime().after(projectTask.getEndTime())) {
				projectTask.setFailReason("1");
				failList.add(projectTask);
				continue;
			}
			//校验名称重复，首先是excel里面，同一个任务组下面不能有重复名称
			for (int j = 0; j < list.size(); j++) {
				ProjectTask projectTask2 = list.get(j);
				if (i != j && projectTask.getGroupName().equals(projectTask2.getGroupName()) 
						&& projectTask.getName().equals(projectTask2.getName())) {
					projectTask.setFailReason("2");
					failList.add(projectTask);
					break;
				}
			}
			//其次跟数据库里相比较，同一个任务组不能有重复名称
			if (StringUtils.isEmpty(projectTask.getFailReason())) {
				projectTask.setProject(project);
				ProjectTask result = dao.getByProjectAndGroup(projectTask);
				if (null != result) {
					projectTask.setFailReason("3");
					failList.add(projectTask);
					continue;
				}
				validList.add(projectTask);
			}
		}
		preview.setValidList(validList);
		preview.setFailList(failList);
		//将file上传到缓存
		if (validList.size() > 0) {
			String key = IdGen.uuid();
			EhCacheUtils.put("temp", key, validList);
			preview.setKey(key);
		}
		return preview;
	}
	
	
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public void importBatch(List<ProjectTask> list){
		//遍历List，查询是否需要新建任务组
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				ProjectTask projectTask = list.get(i);
				TaskGroup param = new TaskGroup();
				param.setName(projectTask.getGroupName());
				param.setProject(projectTask.getProject());
				TaskGroup taskGroup = taskGroupService.getByName(param);
				if (null == taskGroup) {
					taskGroupService.save(param);
					projectTask.setTaskGroup(param);
				}else {
					projectTask.setTaskGroup(taskGroup);
				}
				super.save(projectTask);
			}
		}
		//是否需要发送邮件
	}
}